

import {getStore,setStore, setState} from '@/common/util';
import { getWsUrl} from "@/common/env.config";
import {WebSocket} from '@/common/socket.js'
import {getMessages} from '@/api/mcenter/index'

const actionText = {
	"upvote": "点赞&&评论",
	"express":"物流信息",
	"verify":"新审核",
	"newfans":"新审核",
};


const message = {
	state: {
		sendedMsgCount: getStore({
			name: 'sendedCount'
		}) || {
			sendedTime: new Date(),
			count: 0
		},
		unreadMsgCount:getStore({
		  name: '$unReadMessageCount'
		}) || 0,
		messages: getStore({
		  name: '$messages'
		}) ||  [],
		friends: getStore({
		name: '$friends'
		}) || [],
		websocket: null,
		
	},
	mutations: {
		SET_WEBSOCKET(state, websocket) {
			state.websocket = websocket;
		},
		UPDATE_SENDED_MSG_COUNT(state, data) {
			state.sendedMsgCount = data;
		},
		SET_SOCKETTASK(state, webscoket) {
			state.webscoket = webscoket;
		},
		SET_UNREAD_MESSAGE(state,data) {
			state.unreadMsgCount= state.unreadMsgCount+data;
			setStore({
			name: '$unReadMessageCount',
			content: state.unreadMsgCount,
			type: 'session'
			})
		},
		SET_MESSAGES(state, data) {
			let index = state.messages.findIndex(o => o.fromPartyId == data.fromPartyId);
			
			console.log("ADD_MESSAGE_ITEM begin:" +JSON.stringify(data));
			if(index !== -1) {
				data.count = state.messages[index].count + 1;
				state.messages.splice(index, 1);
			} else {
				data.count = 1
			}
			state.messages.unshift(data);
			
			setStore({
				name: '$messages',
				content: state.messages,
				type: 'session'
			})
		},
		UPDATE_MESSAGE_ITEM(state, data) {
			const {
				index,
				key,
				value
			} = data;
			state.messages[index][key] = value;
			console.log("begin:" +JSON.stringify(state.messages));
			setStore({
				name: '$messages',
				content: state.messages,
				type: 'session'
			})
			
			console.log("end:" +JSON.stringify(state.messages));
		},
		SET_FRIENDS(state, data) {
			console.log("set friends" + data);
			if(state.friends.length <= 0)
			{
				state.friends.push({friendId: data.friendId, chatRecords:[data.chatRecord]});
			} else {
				let index = state.friends.findIndex(o => o.friendId == data.fromPartyId);
				if(index !== -1)
				{
					state.friends.push({friendId: data.friendId, chatRecords:[data.chatRecord]});
				} else 
				{
					state.friends[index].chatRecords.push(data.chatRecord)
				}
				
			}
			
			setStore({
				name: '$friends',
				content: state.friends,
				type: 'session'
			})
		},
		SET_FRIEND_CHATRECODES(state, data) {
			let index = state.friends.findIndex(o => o.friendId == data.friendId);
			state.friends[index].splice(0, 0, data.chatRecords);
		},
		DELETE_MESSAGES(state, index) {
			console.log("DELETE_MESSAGES")
			if(index !== -1)
			{
				state.messages.splice(index, 1);
				setStore({
					name: '$messages',
					content: state.messages,
					type: 'session'
				})
			}

		},
		clear_messages(state, data) {
			state.messages = []
			setStore({
				name: '$messages',
				content: [],
				type: 'session'
			})
			state.friends = []
			setStore({
				name: '$friends',
				content: state.friends,
				type: 'session'
			})
		}
		
	},
	actions: {
		connect: function({commit, state}, data) {
			var websocket = new WebSocket()
			console.log("wsurl:"+getWsUrl())
			
			websocket.buildConnect(getWsUrl(), function() {
				websocket.buildConnect()
			});
			var startTime = new Date().getTime();
			setTimeout(function () {
				websocket.setMessageMonitor('/topic/notice', function(response) {
					console.log("From MQ:"+ response.body);
					if(response.body !== undefined && response.body.length > 0)
					{
						var data = JSON.parse(response.body);
						//var index = state.messages.findIndex(p => p.chatId == "-1")
						data.fromPartyId = "-1";
						data.fromNickName="系统通知"
						data.fromImgUrl="../../static/image/my/notify/notify.png"
						data.msgType = "TEXT";
						data.chatType = "NOTIFY"
						console.log("/topic/notice")
						commit("SET_MESSAGES", data)
						commit("SET_UNREAD_MESSAGE",1)
					}
				})
				if(data !== undefined&& data.userId !== undefined && data.userId.length > 0)
				{
					console.log('/user/'+data.userId+'/topic/chat')
					websocket.setMessageMonitor('/user/'+data.userId+'/topic/chat', function(response) {
						console.log("From topic chat:"+ response.body);
						if(response.body !== undefined && response.body.length > 0){
							var item = JSON.parse(response.body);
							item.chatType = "CHAT"
							commit("SET_MESSAGES", item)
							commit("SET_UNREAD_MESSAGE",1)
							item.user = "customer";
							console.log("/topic/notice/chatrecord")

							commit("SET_FRIENDS",{friendId: item.fromPartyId, chatRecord: item});
						}
							
					})
					websocket.setMessageMonitor('/user/'+data.userId+'/topic/action', function(response) {
						
						if(response.body !== undefined && response.body.length > 0)
						{
							var item= JSON.parse(response.body);
 							item.fromPartyId = item.actionType;
							item.fromNickName = actionText[item.actionType]
// 							item.fromNickName = "评论&&点赞"
							item.fromImgUrl="../../static/image/my/image/notify/"+item.actionType+".png"
							item.msgType = "TEXT";
							item.chatType = "ACTION"
							commit("SET_MESSAGES", item)
							commit("SET_UNREAD_MESSAGE",1)
						}
					})
				}
			}, 600)
			
			setTimeout(function() {
				websocket.isNeedReconnection = false;
			}, 6000)
				
			commit("SET_WEBSOCKET", websocket);
		},
		closeWebSocket: function({commit, state}) {
			if(state.webscoket != null) {
				state.websocket.close();
			}
			commit("SET_WEBSOCKET", null);
		},
		
		clearUnreadCount: function({commit, state}, data) {
			let index = state.friends.findIndex(p => p.fromPartyId == data);
			if(index !== -1) {
				var count = state.unreadMsgCount;
				commit("SET_UNREAD_MESSAGE", (-1)*count);
				commit("UPDATE_MESSAGE_ITEM", {index: index, key: "count", value: 0})
			}
		},
		updateFreindsMessageAction: function({commit, state}, data) {
			commit("UPDATE_MESSAGE_ITEM",data);
		},
		deleteFriedsMessageAction: function({commit, state}, data) {
			commit("DELETE_MESSAGES", data.index)
		},
		getFriendHistoryRecords: function({commit,state}, data) {
			return new Promise((resolve, reject) => {
				getMessages(data).then(response => {
					console.log(JSON.stringify(response));
					if(response !== null && response.length > 0) {
						commit("SET_FRIEND_CHATRECODES", {friendId: data.fromPartyId, chatRecords: response})
					}
					resolve();
				}).catch(error => {
						reject(error)
					})
			});
		}
	} 
}

export default message;